# *-* coding:utf8 *-*
from info import constants
from info.models import User, News, Category
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import index_blu
from flask import render_template, session, current_app, request, g
from flask import current_app,jsonify


@index_blu.route('/')
@user_login_data
def hello_world():
    user = g.user
    news_list = None
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
    # 点击排行
    click_news_list = list()
    for i in news_list:
        click_news_list.append(i.to_basic_dict())
    # 获取新闻分类数据
    categories = Category.query.all()
    # print(categories)
    categories_dicts = []
    for category in categories:
        categories_dicts.append(category.to_dict())

    data = {
        "user_info": user.to_dict() if user else None,
        'click_news_list':click_news_list,
        'categories':categories_dicts

    }
    # print(categories_dicts)
    # print(click_news_list)
    # print(user.to_dict())
    # print(categories_dicts)


    return render_template('news/index.html',data = data)


@index_blu.route('/newslist')
def news_list():
    """
    :return:
    """
    # 获取参数
    args_dict = request.args
    page = args_dict.get('p','1')
    per_page = args_dict.get('per_page',constants.HOME_PAGE_MAX_NEWS)
    category_id = args_dict.get('cid','1')

    # 检验参数
    try:
        page = int(page)
        per_page = int(per_page)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.PARAMERR,errmsg = '参数错误')

    filters = [News.status == 0]
    # 如果分类id不为0，那么添加分类id的过滤
    if category_id != "1":
        filters.append(News.category_id == category_id)

    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,per_page,False)


    except Exception as e:
        current_app.logger.error(e)


        return jsonify(errno = RET.DBERR,errmsg = '数据查询失败')
    # 查询出来的数据
    itmes = paginate.items

    total_page = paginate.pages
    current_page = paginate.page

    news_li = list()

    for news in itmes:
        news_li.append(news.to_basic_dict())

    return jsonify(errno=RET.OK, errmsg="OK", totalPage=total_page, currentPage=current_page, newsList=news_li,
                       cid=category_id)